package com.dhcc.sds.busi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.entity.CdcDiagnosisEntity;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.busi.entity.CdcEpisodeEntity;
import com.dhcc.cdc.busi.service.ICdcDiagnosisService;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.dao.CdcProductMapper;
import com.dhcc.cdc.sys.dao.DictionaryMapper;
import com.dhcc.cdc.sys.dao.DictypeMapper;
import com.dhcc.cdc.sys.entity.CdcProductEntity;
import com.dhcc.cdc.sys.entity.ConfigurationEntity;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.entity.DictypeEntity;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.SpringContextHolder;
import com.dhcc.core.framework.util.collect.MapUtil;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.sds.base.cache.qcentity.QcEntityCache;
import com.dhcc.sds.base.dao.SdsQcentityMapper;
import com.dhcc.sds.base.entity.SdsExpressEntity;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.entity.SdsQcentityRuleEntity;
import com.dhcc.sds.base.function.GetEntrySrv;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsExpressService;
import com.dhcc.sds.base.service.ISdsQcentityRuleService;
import com.dhcc.sds.busi.dao.SdsQcincaseMapper;
import com.dhcc.sds.busi.dto.AnalysisIndexDto;
import com.dhcc.sds.busi.dto.STEMIIndexStaDto;
import com.dhcc.sds.busi.dto.SdsFillByDoctorDto;
import com.dhcc.sds.busi.dto.SdsQcincaseDto;
import com.dhcc.sds.busi.entity.SdsQcincaseEntity;
import com.dhcc.sds.busi.entity.SdsQcincaseOperlogEntity;
import com.dhcc.sds.busi.service.ISdsQcfitemExecresultService;
import com.dhcc.sds.busi.service.ISdsQcincaseOperlogService;
import com.dhcc.sds.busi.service.ISdsQcincaseService;
import com.dhcc.sds.busi.vo.AnalysisSdsPortalVo;
import com.dhcc.sds.busi.vo.SdsOPQcincaseVo;
import com.dhcc.sds.util.DateUtil;
import com.dhcc.sds.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 病种入组病例表数据服务层接口
 *
 * @author sunyingjie
 * @ClassName: SdsQcincaseServiceImpl
 * @Description: TODO
 * @date 2021-03-22 10:09:15
 */
@Service("sdsQcincaseService")
public class SdsQcincaseServiceImpl extends BaseServiceImpl<SdsQcincaseMapper, SdsQcincaseEntity> implements ISdsQcincaseService {

    @Autowired
    private ICdcEpisodeService cdcEpisodeService;

    @Autowired
    private SdsQcentityMapper sdsQcentityMapper;

    @Autowired
    private IDictionaryService dictionaryService;

    @Autowired
    private ISdsCommonService sdsCommonService;

    @Autowired
    private IConfigurationService configurationService;
    @Autowired
    private ICdcDictionaryService cdcDictionaryService;
    @Autowired
    private ISdsQcincaseOperlogService sdsQcincaseOperlogService;
    @Autowired
    private CdcProductMapper productMapper;
    @Autowired
    private DictypeMapper dictypeMapper;
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private ISdsQcfitemExecresultService sdsQcfitemExecresultService;
    @Autowired
    private SdsQcincaseMapper sdsQcincaseMapper;
    @Autowired
    private ISdsQcentityRuleService sdsQcentityRuleService;
    @Autowired 
    private ISdsExpressService sdsExpressService;
    @Autowired 
    private ICdcDiagnosisService cdcDiagnosisService;

    @Override
    public List<SdsQcincaseEntity> page(Page<SdsQcincaseEntity> page, Map<String, Object> map) {
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        map.put("userLinkDepts", deptIds);
        Object abbrev = map.get("abbrev");
        Object dateType = map.get("dateType");
        Object startDate = map.get("startDate");
        Object endDate = map.get("endDate");
        Object fillingStatus = map.get("fillingStatus");
        String aLong = String.valueOf(abbrev);
        if ("null".equals(aLong)) {
            return null;
        }

        // 单病种医生是否可以直接上报配置
        String formCheckType = CdcConfigCache.me().getValueByKey("SDS", "SDFormCheckType");
        String sqlStr = "";
        if (CommonUtil.isNotEmpty(map.get("searchType"))) {
            switch (map.get("searchType").toString()) {
                case "notReported":
                    if (CommonUtil.equals(formCheckType, "Y")) {
                        sqlStr = "and (state = 'I' or state = 'Save' or state = 'Back' or state = 'Submit' or state = 'Check') ";
                    } else {
                        sqlStr = "and (state = 'I' or state = 'Save' or state = 'Back') ";
                    }
                    break;
                case "reported":
                    sqlStr = "and state = 'Up' ";
                case "notChecked":
                    sqlStr = "and state = 'Submit' ";
                    break;
                case "checked":
                    sqlStr = "and state = 'Check' ";
                    break;
                default:
                    break;
            }
            map.put("searchType", sqlStr);
        }
        SdsQcentityEntity sdsQcentityEntity = new SdsQcentityEntity();
        sdsQcentityEntity.setAbbrev(aLong);
        SdsQcentityEntity sdsQcentityEntity1 = sdsQcentityMapper.selectOne(sdsQcentityEntity);
        String s = String.valueOf(dateType);
        String s1 = String.valueOf(startDate);
        String s2 = String.valueOf(endDate);
        String s3 = String.valueOf(fillingStatus);
        if (StringUtils.isEmpty(s3)) {
            //已排除
            map.put("state", "O");
        }

        List<CdcEpisodeEntity> cdcEpisodeEntities = cdcEpisodeService.listByDate(s, s1, s2, map);
        List<SdsQcincaseEntity> page1 = this.baseMapper.page(page, map);
        List<SdsQcincaseEntity> res = new ArrayList<>();

        String baseDateForDelayed = CdcConfigCache.me().getValueByKey("SDS", "BaseDateForDelayed", "2");

        for (SdsQcincaseEntity sdsQcincaseEntity : page1) {
            for (CdcEpisodeEntity cdcEpisodeEntity : cdcEpisodeEntities) {
                if (ObjectUtil.equal(sdsQcincaseEntity.getEpisodeId(), cdcEpisodeEntity.getId())
                        && ObjectUtil.equal(sdsQcentityEntity1.getId(), sdsQcincaseEntity.getEntityId())) {
                    sdsQcincaseEntity.setMrNum(cdcEpisodeEntity.getMrNum());
                    sdsQcincaseEntity.setName(cdcEpisodeEntity.getName());
                    sdsQcincaseEntity.setAdmDate(cdcEpisodeEntity.getAdmDate());
                    sdsQcincaseEntity.setDishDate(cdcEpisodeEntity.getDishDate());
                    sdsQcincaseEntity.setAdmLocDesc(cdcEpisodeEntity.getAdmLocDesc());
                    sdsQcincaseEntity.setAdmDoctorName(cdcEpisodeEntity.getAdmDoctorName());
                    sdsQcincaseEntity.setFillingStatusDesc(sdsCommonService.getDictDesc("SDQCFillingStatus", sdsQcincaseEntity.getFillingStatus()));
                    sdsQcincaseEntity.setReportStatusDesc(sdsCommonService.getDictDesc("SDQCReportStatus", sdsQcincaseEntity.getReportStatus()));
                    sdsQcincaseEntity.setGroupStatusDesc(sdsCommonService.getDictDesc("SDQCGroupStatus", sdsQcincaseEntity.getGroupStatus()));
                    if (CommonUtil.equals(baseDateForDelayed, "1")) {
                        if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up") && CommonUtil.isNotEmpty(cdcEpisodeEntity.getDishDate())) {
                            sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), cdcEpisodeEntity.getDishDate(), "d")));
                        }
                    } else if(CommonUtil.equals(baseDateForDelayed, "2")) {
                        if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up") && CommonUtil.isNotEmpty(cdcEpisodeEntity.getCodeDate())) {
                            sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), cdcEpisodeEntity.getCodeDate(), "d")));
                        }
                    } else if(CommonUtil.equals(baseDateForDelayed, "3")) {
                        if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up") && CommonUtil.isNotEmpty(cdcEpisodeEntity.getCodeDate())) {
                            sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), DateUtil.parseTime(sdsQcincaseEntity.getInDate()+" "+sdsQcincaseEntity.getInTime()), "d")));
                        }
                    }
                    res.add(sdsQcincaseEntity);
                }
            }
        }

        return res;
    }

    //迟报
    @Override
    public List<SdsQcincaseEntity> getDelayReport(Page<SdsQcincaseEntity> page, Map<String, Object> params) {


        CdcProductEntity productEntity = new CdcProductEntity();
        productEntity.setCode("SDS");
        productEntity = productMapper.selectOne(productEntity);

        DictypeEntity dicType = new DictypeEntity();
        ArrayList<String> codes=new ArrayList<>();
        codes.add("SDQCFillingStatus");
        codes.add("SDQCReportStatus");
        codes.add("SDQCGroupStatus");
        Wrapper<DictypeEntity> dictypeWrapper=new EntityWrapper<>();
        dictypeWrapper.eq("product_id",productEntity.getId());
        dictypeWrapper.in("code",codes);
        List<DictypeEntity> dictypeEntities = dictypeMapper.selectList(dictypeWrapper);
        List<Long> dictypeIds = dictypeEntities.stream().map(DictypeEntity::getId).collect(Collectors.toList());


        Wrapper<DictionaryEntity> dictionaryWrapper=new EntityWrapper<>();
        dictionaryWrapper.in("dictype_id",dictypeIds);
        List<DictionaryEntity> dicList =  dictionaryMapper.selectList(dictionaryWrapper);
        Map<String, String> dicMap = dicList.stream().collect(Collectors.toMap(DictionaryEntity::getCode, DictionaryEntity::getDescription));

        String baseDateForDelayed = CdcConfigCache.me().getValueByKey("SDS", "BaseDateForDelayed", "2");
        List<SdsQcincaseEntity> res = null;
        res = this.baseMapper.selectDelayReport(page,params);
        for (SdsQcincaseEntity sdsQcincaseEntity : res) {
            sdsQcincaseEntity.setFillingStatusDesc(dicMap.get(sdsQcincaseEntity.getFillingStatus()));
            sdsQcincaseEntity.setReportStatusDesc(dicMap.get(sdsQcincaseEntity.getReportStatus()));
            sdsQcincaseEntity.setGroupStatusDesc(dicMap.get(sdsQcincaseEntity.getGroupStatus()));
            if (CommonUtil.equals(baseDateForDelayed, "1")) {
                if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up") && CommonUtil.isNotEmpty(sdsQcincaseEntity.getDishDate())) {
                    sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getDishDate(), "d")));
                }
            } else if(CommonUtil.equals(baseDateForDelayed, "2")){
                if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up") && CommonUtil.isNotEmpty(sdsQcincaseEntity.getCodeDate())) {
                    sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getCodeDate(), "d")));
                }
            } else if(CommonUtil.equals(baseDateForDelayed, "3")){
                if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up") && CommonUtil.isNotEmpty(sdsQcincaseEntity.getCodeDate())) {
                    sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getInDate(), "d")));
                }
            }
        }
        return res;
    }


    @Override
    public List<SdsQcincaseEntity> list(Map<String, Object> map) {
        return this.baseMapper.list(map);
    }

    @Override
    public List<SdsQcincaseEntity> listByDate(Map<String, Object> params, String dateType, String startDate, String endDate) {
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        List<CdcEpisodeEntity> cdcEpisodeEntities = cdcEpisodeService.listByDate(dateType, startDate, endDate, params);
        List<SdsQcincaseEntity> list = this.baseMapper.list(params);
        Wrapper<SdsQcentityEntity> entityWpr = new EntityWrapper<>();
        entityWpr.ne("is_active", 0);// 排除无效病种
        List<SdsQcentityEntity> list1 = sdsQcentityMapper.selectList(entityWpr);

        List<SdsQcincaseEntity> result = new ArrayList<>();
        for (SdsQcincaseEntity sdsQcincaseEntity : list) {
            for (CdcEpisodeEntity cdcEpisodeEntity : cdcEpisodeEntities) {
                if (sdsQcincaseEntity.getEpisodeId().equals(cdcEpisodeEntity.getId())) {
                    result.add(sdsQcincaseEntity);
                }
            }
        }

        // 单病种医生是否可以直接上报配置
        String formCheckType = CdcConfigCache.me().getValueByKey("SDS", "SDFormCheckType");

        for (SdsQcentityEntity sdsQcentityEntity : list1) {
            int i = 0;
            int y = 0;
            int noCheck = 0;
            int checked = 0;
            int testCount = 0;
            for (SdsQcincaseEntity sdsQcincaseEntity : result) {
                if (sdsQcentityEntity.getId().equals(sdsQcincaseEntity.getEntityId())) {
                    String status = sdsQcincaseEntity.getState();
                    if ("I".equals(status) || "Save".equals(status) || "Back".equals(status)) {
                        //待填报
                        sdsQcentityEntity.setNotReported(++i);
                    } else if ("Up".equals(status)) {
                        //已上报
                        sdsQcentityEntity.setReported(++y);
                    } else if ("Check".equals(status)) {
                        // 如果允许医生直接上报，则没有审核流程
                        if (CommonUtil.equals(formCheckType, "Y")) {
                            //待填报
                            sdsQcentityEntity.setNotReported(++i);
                        } else {
                            // 已审核
                            sdsQcentityEntity.setChecked(++checked);
                        }
                    } else if ("Submit".equals(status)) {
                        // 如果允许医生直接上报，则没有审核流程
                        if (CommonUtil.equals(formCheckType, "Y")) {
                            //待填报
                            sdsQcentityEntity.setNotReported(++i);
                        } else {
                            // 未审核
                            sdsQcentityEntity.setNotChecked(++noCheck);
                        }
                    }
                    // 测试上报例数
                    if (sdsQcincaseEntity.getTestFlg() == 1) {
                        sdsQcentityEntity.setTestCount(testCount++);
                    }
                }
            }
        }

        if (null == result || result.size() == 0) {
            SdsQcincaseEntity sdsQcincaseEntity = new SdsQcincaseEntity();
            sdsQcincaseEntity.setSdsQcentityEntities(list1);
            result.add(sdsQcincaseEntity);
        } else {
            SdsQcincaseEntity sdsQcincaseEntity = result.get(0);
            sdsQcincaseEntity.setSdsQcentityEntities(list1);
        }
        return result;
    }

    @Override
    public JSONObject getStatusMapByType(String type) {
        JSONObject jsObj = new JSONObject();
        jsObj.put("", "");
        List<DictionaryEntity> sds = dictionaryService.queryByTypeCode("SDS", type);
        for (DictionaryEntity dic : sds) {
            jsObj.put(dic.getCode(), dic.getDescription());
        }
        return jsObj;
    }

    @Override
    public void deleteStatusById(Long sdsQcincaseId) {
        SdsQcincaseEntity sdsQcincaseEntity = this.baseMapper.selectById(sdsQcincaseId);

        //已排除
        //当前状态
        sdsQcincaseEntity.setState("O");
        this.baseMapper.updateById(sdsQcincaseEntity);
    }

    @Override
    public Long isGroup(Long episodeId) {
        Long res = null;
        List<SdsQcincaseEntity> qcincaseEntities = this.baseMapper.selectList(new EntityWrapper<SdsQcincaseEntity>()
                .eq("episode_id", episodeId));
        if (!qcincaseEntities.isEmpty()) {
            for (SdsQcincaseEntity sdsQcincaseEntity : qcincaseEntities) {
                if (!Objects.equals("O", sdsQcincaseEntity.getState())) {
                    res = sdsQcincaseEntity.getId();
                    break;
                }
            }
        }
        return res;
    }

    @Override
    public JSONArray getYearMap() {
        List<String> years = this.baseMapper.selectYears();
        JSONArray yearsArry = new JSONArray();
        for (String s : years) {
            JSONObject yearsObj = new JSONObject();
            yearsObj.put("value", s);
            yearsObj.put("text", s);
            yearsArry.add(yearsObj);
        }
        return yearsArry;
    }

    @Override
    public JSONArray getMonthMap() {
        JSONArray monthsArry = new JSONArray();
        JSONObject obj1 = new JSONObject();
        obj1.put("value", "");
        obj1.put("text", "全部");
        monthsArry.add(obj1);
        for (int i = 1; i < 13; i++) {
            JSONObject obj = new JSONObject();
            obj.put("value", i);
            obj.put("text", i);
            monthsArry.add(obj);
        }
        return monthsArry;
    }

    @Override
    public List<STEMIIndexStaDto> getIndexDatas(Map<String, Object> params) {
        return this.baseMapper.selectIndexDatas(params);
    }

    @Override
    public List<Long> getIndexNums(Map<String, Object> params) {
        return this.baseMapper.selectIndexNums(params);
    }

    @Override
    public SdsQcincaseEntity selectByEpisodeId(Map<String, Object> params) {
        return this.baseMapper.getByEpisodeId(params);
    }

    @Override
    public SdsQcincaseEntity selectEntityByEpisodeId(Long episodeId) {
        return sdsQcincaseMapper.getEntityByEpisodeId(episodeId);
    }

    @Override
    public SdsQcincaseEntity selectByEpisodeIdAndEntityId(Long episodeId, Long entityId) {
        return sdsQcincaseMapper.getByEpisodeIdAndEntityId(episodeId,entityId);
    }

    @Override
    public List<AnalysisIndexDto> getAnalysisIndexDatas(Map<String, Object> params) {
        return this.baseMapper.selectAnalysisIndexDatas(params);
    }

    @Override
    public Map<String, Object> listByDate2(Map<String, Object> params) {
        Map<String, Object> entityMap = new HashMap();
        List<SdsQcincaseEntity> result = new ArrayList<>();
        // 查询登录用户关联科室
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        List<SdsQcincaseEntity> mrlist = this.baseMapper.getMrlistOfDept(params);

        // 单病种医生是否可以直接上报配置
        String formCheckType = CdcConfigCache.me().getValueByKey("SDS", "SDFormCheckType");

        Long entityTypeId = sdsCommonService.getDictId("QcentityType","Up");
        Wrapper<SdsQcentityEntity> entityWpr = new EntityWrapper<>();
        entityWpr.eq("entity_type_id",entityTypeId).ne("is_active", 0).orderBy("ind_no");// 排除无效病种
        List<SdsQcentityEntity> list1 = sdsQcentityMapper.selectList(entityWpr);
        //int patientNum = this.baseMapper.getMrlistOfDeptCount(params);
        //就诊类型:住院
        CdcDictionaryEntity admType = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_type", "I");
        int patientNum = 0;
        for (SdsQcentityEntity sdsQcentityEntity : list1) {
            int i = 0;
            int y = 0;
            int noCheck = 0;
            int checked = 0;
            int testCount = 0;
            int uploadSuccess = 0;
            int uploadFailure = 0;
            a:
            for (SdsQcincaseEntity qcincaseEntity : mrlist) {
                //add 只查询住院病人
                /*CdcEpisodeEntity cdcEpisodeEntity = cdcEpisodeService.selectById(qcincaseEntity.getEpisodeId());
                if (!Objects.equals(cdcEpisodeEntity.getBusAdmTypeId(), admType.getId())){
                    continue a;
                }
                patientNum++;*/

                if (Objects.equals(sdsQcentityEntity.getId(), qcincaseEntity.getEntityId())) {
                    String status = qcincaseEntity.getState();
                    if ("I".equals(status) || "Save".equals(status) || "Back".equals(status)) {
                        //待填报
                        sdsQcentityEntity.setNotReported(++i);
                    } else if ("Up".equals(status)) {
                        //已上报
                        sdsQcentityEntity.setReported(++y);
                        if (qcincaseEntity.getReportState() == null) {

                        } else if (qcincaseEntity.getReportState() == 2) {
                            // 上传国家平台成功
                            sdsQcentityEntity.setUploadSuccess(++uploadSuccess);
                        } else if (qcincaseEntity.getReportState() == 4) {
                            // 上传国家平台失败
                            sdsQcentityEntity.setUploadFailure(++uploadFailure);
                        }
                    } else if ("Check".equals(status)) {
                        // 如果允许医生直接上报，则没有审核流程
                        if (CommonUtil.equals(formCheckType, "Y")) {
                            //待填报
                            sdsQcentityEntity.setNotReported(++i);
                        } else {
                            // 已审核
                            sdsQcentityEntity.setChecked(++checked);
                        }
                    } else if ("Submit".equals(status)) {
                        // 如果允许医生直接上报，则没有审核流程
                        if (CommonUtil.equals(formCheckType, "Y")) {
                            //待填报
                            sdsQcentityEntity.setNotReported(++i);
                        } else {
                            // 未审核
                            sdsQcentityEntity.setNotChecked(++noCheck);
                        }
                    }
                    // 测试上报例数
                    if (qcincaseEntity.getTestFlg() == 1) {
                        sdsQcentityEntity.setTestCount(testCount++);
                    }
                }
            }
        }
        entityMap.put("patientNum", mrlist.size());
        entityMap.put("data", list1);

        return entityMap;
    }

    @Override
    public List<SdsQcincaseEntity> page2(Page<SdsQcincaseEntity> page, Map<String, Object> params) {
        List<SdsQcincaseEntity> result = new ArrayList<>();
        Object entityId = params.get("entityId");
        if (CommonUtil.isEmpty(params.get("status"))) {
            return result;
        }
        Object searchType = params.get("searchType");
        Object startDate = params.get("startDate");
        Object endDate = params.get("endDate");
        Object status = params.get("status");
        Object mrNum = params.get("mrNum");
        Object name = params.get("name");
        Object admLocDesc = params.get("admLocDesc");
        Object admDoctorName = params.get("admDoctorName");
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        params.put("mrNum", mrNum);
        params.put("name", name);
        params.put("admLocDesc", admLocDesc);
        params.put("admDoctorName", admDoctorName);

        // 单病种医生是否可以直接上报配置
        String formCheckType = CdcConfigCache.me().getValueByKey("SDS", "SDFormCheckType");
        String sqlStr = "";
        if (CommonUtil.isNotEmpty(status)) {
            switch (status.toString()) {
                case "notReported":
                    if (CommonUtil.equals(formCheckType, "Y")) {
                        sqlStr = "and (state = 'I' or state = 'Save' or state = 'Back' or state = 'Submit' or state = 'Check') ";
                    } else {
                        sqlStr = "and (state = 'I' or state = 'Save' or state = 'Back') ";
                    }
                    break;
                case "reported":
                    sqlStr = "and state = 'Up' ";
                    break;
                case "notChecked":
                    sqlStr = "and state = 'Submit' ";
                    break;
                case "checked":
                    sqlStr = "and state = 'Check' ";
                    break;
                case "uploadSuccess":
                    sqlStr = "and state = 'Up' and report_state = 2";
                    break;
                case "uploadFailure":
                    sqlStr = "and state = 'Up' and report_state = 4";
                    break;
                default:
                    break;
            }
            params.put("stateSql", sqlStr);
        }
        result = this.baseMapper.selectMrlist(page, params);

        String baseDateForDelayed = CdcConfigCache.me().getValueByKey("SDS", "BaseDateForDelayed", "2");
        for (SdsQcincaseEntity sdsQcincaseEntity : result) {
            if (CommonUtil.equals(baseDateForDelayed, "1")) {
                if (CommonUtil.isNotEmpty(sdsQcincaseEntity.getDishDate())) {
                    if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up")) {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getDishDate(), "d")));
                    } else {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(sdsQcincaseEntity.getReportDate(), sdsQcincaseEntity.getDishDate(), "d")));
                    }
                }
            } else if(CommonUtil.equals(baseDateForDelayed, "2")){
                if (CommonUtil.isNotEmpty(sdsQcincaseEntity.getCodeDate())) {
                    if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up")) {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getCodeDate(), "d")));
                    } else {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(sdsQcincaseEntity.getReportDate(), sdsQcincaseEntity.getCodeDate(), "d")));
                    }
                }
            } else if(CommonUtil.equals(baseDateForDelayed, "3")){
                if (CommonUtil.isNotEmpty(sdsQcincaseEntity.getInDate())) {
                    if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up")) {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getInDate(), "d")));
                    } else {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(sdsQcincaseEntity.getReportDate(), sdsQcincaseEntity.getInDate(), "d")));
                    }
                }
            }

            sdsQcincaseEntity.setFillingStatusDesc(sdsCommonService.getDictDesc("SDQCFillingStatus", sdsQcincaseEntity.getFillingStatus()));
            sdsQcincaseEntity.setReportStatusDesc(sdsCommonService.getDictDesc("SDQCReportStatus", sdsQcincaseEntity.getReportStatus()));
            sdsQcincaseEntity.setGroupStatusDesc(sdsCommonService.getDictDesc("SDQCGroupStatus", sdsQcincaseEntity.getGroupStatus()));
            if (CommonUtil.equals(sdsQcincaseEntity.getState(), "Up")&&CommonUtil.isNotEmpty(sdsQcincaseEntity.getReportState())) {
                if (sdsQcincaseEntity.getReportState() == 2) {
                    sdsQcincaseEntity.setStateDesc("上报成功");
                } else {
                    sdsQcincaseEntity.setStateDesc("上报失败");
                }
            } else {
                sdsQcincaseEntity.setStateDesc(sdsCommonService.getDictDesc("SDQCMrStatus", sdsQcincaseEntity.getState()));
            }
            sdsQcincaseEntity.setEntityName(QcEntityCache.me().getQcEntityById(sdsQcincaseEntity.getEntityId()).getBtDesc());

//            String reason = sdsQcincaseEntity.getReason();
//            if (CommonUtil.isNotEmpty(reason)) {
//                String[] reasonSplit = reason.split(",");
//                String reaSonStr = "";
//                for (String reasonId : reasonSplit) {
//                    if (CommonUtil.isNotEmpty(reasonId)) {
//                        SdsQcentityRuleEntity sdsQcentityRuleEntity = sdsQcentityRuleService.selectById(reasonId);
//                        SdsExpressEntity sdsExpressEntity = sdsExpressService.selectById(sdsQcentityRuleEntity.getExpressId());
//                        if (!StringUtils.isEmpty(sdsExpressEntity)) {
//                            try {
//                                Class<?> c = Class.forName("com.dhcc.sds.base.function.GetEntrySrv");
//                                GetEntrySrv getEntrySrv = SpringContextHolder.getBean("getEntrySrv");
//                                String methodName = sdsExpressEntity.getExpress() + "Detail";
//                                Method method = c.getMethod(methodName, Long.class, String.class);
//                                String ret = (String) method.invoke(getEntrySrv, sdsQcincaseEntity.getEpisodeId(), sdsQcentityRuleEntity.getParam());
//                                ret = ret.replace("？", "");
//                                reaSonStr += ret + "\n\n";
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                }
//                if (reaSonStr.length() != 0) {
//                    reaSonStr = reaSonStr.substring(0, reaSonStr.length() - 1);
//                }
//                sdsQcincaseEntity.setReason(reaSonStr);
//            }
            sdsQcincaseEntity.setReason("");
            HashMap<String, Object> qryMap = new HashMap<>();
            qryMap.put("episode_id", sdsQcincaseEntity.getEpisodeId());
            qryMap.put("bus_diag_type_id", "1382251829770014721");
            List<CdcDiagnosisEntity> cdcDiagnosisEntities = this.cdcDiagnosisService.selectByMap(qryMap);
            if (cdcDiagnosisEntities.size() != 0) {
                String description = cdcDiagnosisEntities.get(0).getDescription();
                sdsQcincaseEntity.setReason(description);
            }
        }
        return result;
    }

    @Override
    public List<Integer> selectPortalCount(Map<String, Object> params) {
        return this.baseMapper.selectPortalCount(params);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectPortalMrlist(Map<String, Object> params) {
        return this.baseMapper.selectPortalMrlist(params);
    }

    @Override
    public List<Long> selectEntity() {
        return this.baseMapper.selectEntity();
    }

    @Override
    public AnalysisSdsPortalVo selectCostsAndDays(Long entityId, Map<String, Object> params) {
        return this.baseMapper.selectCostsAndDays(entityId, params);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectARatioChartData(Map<String, Object> params) {
        return this.baseMapper.selectARatioChartData(params);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectByStatus(Long entityId, List<String> status, Map<String, Object> params) {
        return this.baseMapper.selectByStatus(entityId, status, params);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectMrInfoByIDs(List<Long> incaseIds) {
        return this.baseMapper.selectMrInfoByIDs(incaseIds);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectPortalCountDetails(String formCheckType, String idName, List<String> deptIds) {
        return this.baseMapper.selectPortalCountDetails(formCheckType, idName, deptIds);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectByCondition(Map<String, Object> params, List<String> statusList) {
        return this.baseMapper.selectByCondition(params, statusList);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectCostsAndDaysByDate(Map<String, Object> params) {
        return this.baseMapper.selectCostsAndDaysByDate(params);
    }

    @Override
    public List<AnalysisSdsPortalVo> getIndexDataByDate(Map<String, Object> params) {
        return this.baseMapper.getIndexDataByDate(params);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectPortalCountDetailsList(String formCheckType, String idName, List<String> deptIds) {
        return this.baseMapper.selectPortalCountDetailsList(formCheckType, idName, deptIds);
    }

    @Override
    public List<AnalysisSdsPortalVo> selectByConditionList(Map<String, Object> params, List<String> statusList) {
        return this.baseMapper.selectByConditionList(params, statusList);
    }

    @Override
    public List<AnalysisSdsPortalVo> getIndexListDataByDate(Map<String, Object> params) {
        return this.baseMapper.getIndexListDataByDate(params);
    }

    @Override
    public CdcEpisodeEntity selectEpisodeByIncaseId(Long incaseId) {
        return this.baseMapper.selectEpisodeByIncaseId(incaseId);
    }

    @Override
    public List<Long> selectIncaseIdsByCondition(Map<String, Object> params, List<String> statusList) {
        return this.baseMapper.selectIncaseIdsByCondition(params, statusList);
    }

    @Override
    public List<SdsOPQcincaseVo> selectOPIncaseByCondition(Map<String, Object> params) {
        return this.baseMapper.selectOPIncaseByCondition(params);
    }

    @Override
    public List<SdsOPQcincaseVo> selectOPIncaseByRegNo(List<Long> incaseIds) {
        return this.baseMapper.selectOPIncaseByRegNo(incaseIds);
    }

    @Override
    public List<SdsQcincaseEntity> selectMrList(Map<String, Object> params) {
        return this.baseMapper.selectMrList(params);
    }

    @Override
    public String getAutoAlias(Long mrId) {
        String res;
        SdsQcincaseEntity sdsQcincaseEntity = this.baseMapper.selectById(mrId);
        int aCount = 0;
        int nCount = 0;
        int eCount = 0;
        if (!StringUtils.isEmpty(sdsQcincaseEntity.getACount())) {
            aCount = sdsQcincaseEntity.getACount();
        }
        if (!StringUtils.isEmpty(sdsQcincaseEntity.getNCount())) {
            nCount = sdsQcincaseEntity.getNCount();
        }
        if (!StringUtils.isEmpty(sdsQcincaseEntity.getECount())) {
            eCount = sdsQcincaseEntity.getECount();
        }
        int tCount = eCount + nCount;
        String r = StrUtil.deciFormat(aCount, tCount);
        res = aCount + ";" + tCount + ";" + r;
        return res;
    }

    @Override
    public Long getMrUseTime(Long mrId) {
        Long xUseTime = 0l;
        SdsQcincaseEntity sdsQcincaseEntity = this.baseMapper.selectById(mrId);
        if (Objects.equals("Save", sdsQcincaseEntity.getState()) || Objects.equals("Submit", sdsQcincaseEntity.getState())
                || Objects.equals("Check", sdsQcincaseEntity.getState()) || Objects.equals("tUp", sdsQcincaseEntity.getState())
                || Objects.equals("Up", sdsQcincaseEntity.getState())) {
            List<String> status = Arrays.asList("Save", "Submit");
            List<SdsQcincaseOperlogEntity> sdsQcincaseOperlogEntities = sdsQcincaseOperlogService.selectUseTime(mrId, status);

            for (SdsQcincaseOperlogEntity sdsQcincaseOperlogEntity : sdsQcincaseOperlogEntities) {
                if (CommonUtil.isEmpty(sdsQcincaseOperlogEntity.getOperStartDate())) {
                    continue;
                }
                Long m = DateUtil.getDateCompare(sdsQcincaseOperlogEntity.getOperDate(), sdsQcincaseOperlogEntity.getOperStartDate(), "m");
                if (m > 30l) {
                    //	单次用时超过30min，不计为有效数据
                    continue;
                }
                xUseTime += m;
            }
        }
        return xUseTime;
    }

    @Override
    public List<SdsQcincaseEntity> selectOPByDimData(Long dimDataId, Long admTypeId) {
        return this.baseMapper.selectOPByDimData(dimDataId, admTypeId);
    }

    @Override
    public Long getEntityIdByEpisodeId(Long episodeId) {
        return this.baseMapper.getEntityIdByEpisodeId(episodeId);
    }

    @Override
    public List<SdsQcincaseEntity> selectContraindicationByAdmStatus(Long id) {
        return this.baseMapper.getContraindicationByAdmStatus(id);
    }


    private void calcEntityDetail(Map<String, Object> mrMap, SdsQcincaseDto entityDto, String formCheckType) {
        String status = mrMap.get("state").toString();
        if ("I".equals(status) || "Save".equals(status) || "Back".equals(status)) {
            //待填报
            entityDto.setNotReported(entityDto.getNotReported() + 1);
        } else if ("Up".equals(status)) {
            //已上报
            entityDto.setReported(entityDto.getReported() + 1);
        } else {
            if ("Check".equals(status)) {
                // 如果允许医生直接上报，则没有审核流程
                if (CommonUtil.equals(formCheckType, "Y")) {
                    //待填报
                    entityDto.setNotReported(entityDto.getNotReported() + 1);
                } else {
                    // 已审核
                    entityDto.setChecked(entityDto.getChecked() + 1);
                }
            } else if ("Submit".equals(status)) {
                // 如果允许医生直接上报，则没有审核流程
                if (CommonUtil.equals(formCheckType, "Y")) {
                    //待填报
                    entityDto.setNotReported(entityDto.getNotReported() + 1);
                } else {
                    // 未审核
                    entityDto.setNotChecked(entityDto.getNotChecked() + 1);
                }
            }
        }
        // 测试上报例数
        if (CommonUtil.equals(mrMap.get("testFlg"), 1)) {
            entityDto.setTestCount(entityDto.getTestCount() + 1);
        }
        // 病种入组人数
        entityDto.setPatientNum(entityDto.getPatientNum() + 1);
    }

    @Override
    public String selectUploadStateByEpisodeId(Map map) {

        List<SdsQcincaseEntity> qcincases = this.baseMapper.list(map);
        if (CommonUtil.isEmpty(qcincases)) {
            return "未入组";
        } else {
            SdsQcincaseEntity qccase = qcincases.get(0);
            if (CommonUtil.isEmpty(qccase)) {
                return "未入组";
            } else {
                if ("Up".equals(qccase.getState())) {
                    return "已上报";
                } else {
                    return "未上报";
                }
            }
        }
    }

    @Override
    public JSONObject getMrListInfo(Map<String, Object> params) {
        JSONObject result = new JSONObject();
        Map<String,Object> map = this.baseMapper.mrlistInfo(params);
        if (MapUtil.isNotEmpty(map)) {
            result = new JSONObject(map);
        }
        return result;
    }

    @Override
    public void changeMrEntity(Map<String, Object> params) {
        Long mrListId = Long.valueOf(params.get("mrListId").toString());
        Long entityId = Long.valueOf(params.get("entityId").toString());
        // 获取当前出院入组记录
        boolean result = false;
        SdsQcincaseEntity mrList = this.selectById(mrListId);
        if (CommonUtil.notEquals(mrList.getEntityId(), entityId)) {
            // 如果选择病种与当前病种不一致，则更新
            mrList.setEntityId(entityId);
            mrList.setIntheMoment("I");
            result = this.updateById(mrList);
            if (result) {
                // 根据数据源配置自动取值
                sdsQcfitemExecresultService.execItemResult(mrListId);
            }
        } else {
            mrList.setIntheMoment("I");
            result = this.updateById(mrList);
        }
        if (result) {
            //增加日志
            String modifyUser = "";
            if (CommonUtil.isNotEmpty(params.get("execUser"))) {
                modifyUser = params.get("execUser").toString();
            } else {
                User user = ShiroKit.getUser();
                modifyUser = user.getLoginName();
            }
            SdsQcincaseOperlogEntity operlog = new SdsQcincaseOperlogEntity();
            operlog.setInCaseId(mrListId);
            operlog.setOperDate(new Date());
            operlog.setOperState("I");
            operlog.setOperResume("在院质控病种和出院入组病种选择确认");
            operlog.setOperUser(modifyUser);
            sdsQcincaseOperlogService.insert(operlog);
        }
    }
}